package crons

import (
	"context"
	"devops-super/internal/service"
	"devops-super/utility/util/cronUtil"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcron"
)

type sCron struct{}

func init() {
	service.RegisterCron(New())
}

func New() *sCron {
	return &sCron{}
}

func (s *sCron) StartCrons(ctx context.Context) (err error) {
	done := make(chan bool)
	err = s.SummaryDatabaseSizeCron(ctx)
	err = s.ClearIoTDataCron(ctx)
	<-done
	return
}

// SummaryDatabaseSizeCron 统计数据库的存储空间
func (s *sCron) SummaryDatabaseSizeCron(ctx context.Context) (err error) {
	express := cronUtil.GetEveryDayCron()
	g.Log().Print(ctx, "Cron:Every Day:AddSummaryDatabaseSize")
	_, err = gcron.AddSingleton(ctx, express, func(ctx context.Context) {
		g.Log().Print(ctx, "execute SummaryDatabaseSize")
		err := s.DoSummaryDatabaseSize(ctx)
		if err != nil {
			return
		}
	}, "SummaryDatabaseSize")
	if err != nil {
		panic(err)
	}
	return
}

func (s *sCron) ClearIoTDataCron(ctx context.Context) (err error) {
	express := cronUtil.GetEveryDayCron()
	g.Log().Print(ctx, "Cron:Every Day:ClearDataCron")
	_, err = gcron.AddSingleton(ctx, express, func(ctx context.Context) {
		g.Log().Print(ctx, "execute ClearDataCron")
		err := s.DoClearIoTData(ctx)
		if err != nil {
			return
		}
	}, "ClearIoTData")
	if err != nil {
		panic(err)
	}
	return
}
